import React, { useState, useRef, useEffect } from 'react';
import { Button, FormInstance, Popconfirm } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { 
  getConsultList, 
  updateConsult, 
  batchUpdateConsult } from '@/services/shop/api';
import { MsgType, showMsg, formatDate, isSupportSticky } from '@/utils/utils';
import ReplayDialog from './ReplayDialog';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl';
import Auditing from '@/components/Auditing';

const Index: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<any>({});
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [ids, setIds] = useState<string[]>([]);
  const auditingRef = useRef();
  const [loading, setLoading] = useState<boolean>(false);
  const [showSpSuccess, setShowSpSuccess] = useState(false);
  const [showSpFail, setShowSpFail] = useState(false);
  const [line, setLine] = useState(-1);

  const columns: ProColumns<SHOPAPI.ShopConsulting>[] = [
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      search: false,
      className: 'wordbreak',
      width: 150
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      width: 200,
      fieldProps: {
        placeholder: '输入商品名称',
      }
    },
    {
      title: '用户账号',
      dataIndex: 'user_name',
      width: 120,
      fieldProps: {
        placeholder: '输入用户账号',
      }
    },
    {
      title: '提问日期',
      dataIndex: 'create_date',
      valueType: 'date',
      hideInTable: true
    },
    {
      title: '咨询问题',
      dataIndex: 'problem',
      search: false,
      width: 120
    },
    {
      title: '咨询回复',
      dataIndex: 'reply',
      search: false,
      width: 120
    },
    {
      title: '处理状态',
      dataIndex: 'status',
      valueType: 'select',
      width: 80,
      valueEnum: {
        U: '待回复',
        S: '已回复',
        C: '已关闭'
      }
    },
    {
      title: '推荐展示',
      dataIndex: 'recommend',
      valueType: 'select',
      width: 70,
      valueEnum: {
        1: '是',
        0: '否'
      },
      search: false
    },
    {
      title: '处理人',
      dataIndex: 'deal_name',
      search: false,
      width: 80,
    },
    {
      title: '处理人工号',
      dataIndex: 'deal_id',
      search: false,
      width: 90,
    },
    {
      title: '处理人时间',
      dataIndex: 'deal_time',
      search: false,
      width: 180,
    },
    {
      title: '是否在列表中展示',
      dataIndex: 'recommend',
      hideInTable: true,
      valueType: 'select',
      valueEnum: {
        1: '是',
        0: '否'
      }
    },
    {
      title: '操作',
      valueType: 'option',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      align: 'center',
      width: 180,
      render: (_, record, index) => [
        record.status === 'U' && <PermissionControl key="replay" action_id="600611002">
          <a key="replay" onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}>回复</a>
        </PermissionControl>,

        record.status === 'U' ? <PermissionControl key="close" action_id="600611006">
          <Popconfirm 
            key="close"
            placement="topRight"
            title="关闭后无法再回复此问题，是否继续？"
            onConfirm={async () => {
              try {
                await updateConsult(Object.assign({}, record, { status: 'C', Action_Id: '600611003' }))
                actionRef.current?.reload()
                showMsg('问题已关闭', MsgType.SUCCESS)
              } catch (error) {
                showMsg(error?.data?.errmsg)
              }
            }}
            okText="确认关闭"
            cancelText="再想想">
            <a onClick={() => {
            }}>关闭</a>
          </Popconfirm> 
        </PermissionControl> : null,

        record.recommend === '1' && record.status === 'S' ?
        <PermissionControl key="cancel" action_id="600611005">
          <Popconfirm 
            key="cancelrecommend"
            placement="topRight"
            title="取消后该问答不会在商品页显示，是否继续？"
            visible={showSpFail && line === index}
            okButtonProps={{
              loading
            }}
            onCancel={() => {
              setShowSpFail(false);
              setLine(-1);
            }}
            onConfirm={async () => {
              const data = Object.assign({}, { consult_id: record.consult_id, recommend: '0', Action_Id: '600611005' });
              setLoading(true);
              auditingRef?.current?.onSign({sign_no: record.consult_id, sign_string: JSON.stringify(data), title: `小程序咨询审批`}, async() => {
                await updateConsult(data).then(res => {
                  setLoading(false);
                  setShowSpFail(false);
                  setLine(-1);
                  showMsg('已取消推荐', MsgType.SUCCESS)
                  actionRef.current?.reload()
                }).catch(error => {
                  setLoading(false);
                  setLine(-1);
                  setShowSpFail(false);
                  showMsg(error?.data?.errmsg);
                });
              });
            }}
            okText="确认取消"
            cancelText="再想想">
              <Auditing
                ref={auditingRef}
                loading={loading}
                module='Z'
                onLoading={e => setLoading(e)}
                onError={() => {
                  setLoading(false);
                  setShowSpFail(false);
                  setLine(-1);
                }}
                onClick={() => {
                  setShowSpFail(true);
                  setLine(index);
                }}
                _html={<a>取消推荐</a>}
              />
          </Popconfirm> 
        </PermissionControl>: null,

        record.recommend === '0' && record.status === 'S' ?
        <PermissionControl key="recommend" action_id="600611004">
          <Popconfirm 
            key="show"
            placement="topRight"
            title="推荐后该问答会在商品页显示，是否继续？"
            okButtonProps={{
              loading
            }}
            visible={showSpSuccess && line === index}
            onConfirm={async () => {
              const data = Object.assign({}, { consult_id: record.consult_id, recommend: '1', Action_Id: '600611004' });
              setLoading(true);
              auditingRef?.current?.onSign({sign_no: record.consult_id, sign_string: JSON.stringify(data), title: `小程序咨询审批`}, async() => {
                await updateConsult(data).then(res => {
                  setLoading(false);
                  setLine(-1);
                  setShowSpSuccess(false);
                  showMsg('已推荐展示', MsgType.SUCCESS)
                  actionRef.current?.reload()
                }).catch(error => {
                  setLoading(false);
                  setShowSpSuccess(false);
                  setLine(-1);
                  showMsg(error?.data?.errmsg);
                });
              });
            }}
            onCancel={() => {
              setShowSpSuccess(false);
              setLine(-1);
            }}
            okText="确认推荐"
            cancelText="再想想">
            <Auditing
              ref={auditingRef}
              loading={loading}
              module='Z'
              onLoading={e => setLoading(e)}
              onError={() => {
                setLoading(false);
                setShowSpSuccess(false);
                setLine(-1);
              }}
              onClick={() => {
                setShowSpSuccess(true);
                setLine(index);
              }}
              _html={<a>推荐展示</a>}
            />
          </Popconfirm>

        </PermissionControl> : null
      ]
    }
  ];

  /**
   * 回复
   * @param fields 
   * @returns 
   */
  const replay = async (fields: SHOPAPI.ShopConsulting) => {
    try {
      await updateConsult({ ...fields, Action_Id: '600611002' })
      actionRef.current?.reload();
      return true;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  };

  /**
   * 批量关闭
   */
  const handleBatchClose = async () => {
    try {
      await batchUpdateConsult({
        consult_ids: ids,
        status: 'C'
      });
      showMsg('问题已关闭', MsgType.SUCCESS);
      setIds([]);
      actionRef.current?.clearSelected?.();
      actionRef.current?.reload();
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  const onRowChange = (selectedRowKeys: React.Key[], selectedRows: SHOPAPI.ShopConsulting[]) => {
    if (!selectedRows.length) {
      setIds([]);
      return
    }
    const rows = selectedRows.map(item => {
      return item.consult_id;
    });
    setIds(rows);
  }

  useEffect(() => {
    formRef.current?.setFieldsValue({
      status: 'U'
    });
    formRef.current?.submit();
  }, [])

  console.log('aaaa', line)

  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}}>
      <ProTable<SHOPAPI.ShopConsulting, SHOPAPI.ShopConsulting & COMMON.PageParams>
        actionRef={actionRef}
        formRef={formRef}
        manualRequest={true}
        bordered
        loading={loading}
        rowKey="consult_id"
        search={{
          span: 6,
          labelWidth: 120,
          collapsed: false,
          collapseRender: () => '',
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [<PermissionControl key="search" action_id="600611001">{dom}</PermissionControl>];
          }
        }}
        request={async (params) => {
          try {
            if (params.create_date) {
              params.create_date = formatDate(params.create_date, 'YYYYMMDD');
            }
            params.recommend = Number(params.recommend)
            const data: SHOPAPI.ShopConsultingList = await getConsultList(params);
            return {
              data: data.record_list,
              success: true,
              total: data.sum_record_num
            };
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0
            };
          }
        }}
        columns={columns}

        rowSelection={{
          columnWidth: 80,
          onChange: onRowChange,
          getCheckboxProps: (record) => {
            return {
              disabled: record.status === 'C'
            }
          }
        }}

        options={false}

        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'add',
                label: <PermissionControl action_id="600611006">
                    <Popconfirm
                      disabled={ids.length === 0}
                      okText="确认关闭" 
                      cancelText="取消"
                      onConfirm={handleBatchClose}
                      title="关闭后无法再回复此问题，是否继续？">
                        <Button disabled={ids.length === 0} type="primary">
                          批量关闭问题
                        </Button>
                    </Popconfirm>
                  </PermissionControl>
              }
            ]
          }
        }}

        pagination={{
          showQuickJumper: true
        }}
        scroll={{
          x: 1200
        }}
      />

      {
        createModalVisible && <ReplayDialog 
        handleAdd={replay} 
        record={currentRow} 
        handleModalVisible={handleModalVisible} />
      }
    </PageContainer>
  );
};

export default Index;
